<template>
  <el-select
    v-model="currValue"
    class="vc-select"
    v-bind="options"
  >
    <el-option
      v-for="item in dataList"
      :key="item.key"
      :value="item.key"
      :label="item.value"
    />
  </el-select>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import visual from "@/visual/js/visual";
import { getDictionary } from '@/utils/system';
import api from "@/http/api";

const props = defineProps({
  node: Object,
  compStyle: Object,
  compData: Object
});
const currNode = ref(props.node);
const currValue = ref(null);
const currDictCode = ref('');
const currDataModelId = ref('');
const currDMValue = ref('');
const currDMLabel = ref('');
const dataList = ref([]);

const init = () => {
  const compStyle = props.compStyle || {};
  if (compStyle['dataSource'] === 'enum') {
    const optionList = [];
    (compStyle['enumValue'] || '').split(',').forEach(item => {
      optionList.push({key: item, value: item});
    });
    dataList.value = optionList;
  } else if (compStyle['dataSource'] === 'dict') {
    currDictCode.value = compStyle['dictCode'] || '';
    loadDictionary(currDictCode.value);
  } else if (compStyle['dataSource'] === 'dataModel') {
    if (currDataModelId.value !== (compStyle['dataModelId'] || '')) {
      currDataModelId.value = compStyle['dataModelId'] || '';
      loadDataModelField(currDataModelId.value, compStyle);
    }
  }

  if (currDataModelId.value
      && (currDataModelId.value !== (compStyle['dataModelId'] || '')
        || currDMValue.value !== (compStyle['value'] || '')
        || currDMLabel.value !== (compStyle['label'] || ''))) {
    currDMValue.value = compStyle['value'] || '';
    currDMLabel.value = compStyle['label'] || '';
    setTimeout(() => loadDataModelData(currDataModelId.value, compStyle), 500);
  }

  if (!props.compData?.dataSourceType) {
    loadValue();
  }
};

const options = computed(() => {
  const compStyle = props.compStyle || {};
  const data = {};
  visual.addIfNotNull(data, compStyle, 'size');
  visual.addIfNotNull(data, compStyle, 'placeholder');
  visual.addIfNotNull(data, compStyle, 'effect');
  visual.addIfNotNull(data, compStyle, 'filterable');
  visual.addIfNotNull(data, compStyle, 'multiple');
  visual.addIfNotNull(data, compStyle, 'allow-create');
  visual.addIfNotNull(data, compStyle, 'fit-input-width');
  visual.addIfNotNull(data, compStyle, 'required');
  visual.addIfNotNull(data, compStyle, 'clearable');
  visual.addIfNotNull(data, compStyle, 'disabled');
  visual.addIfNotNull(data, compStyle, 'autocomplete');

  return data;
});

const loadDictionary = (dictCode) => {
  if (!dictCode) {
    dataList.value = [];
  }

  getDictionary(dictCode).then(res => {
    dataList.value = res;
  });
};

const loadDataModelField = (dataModelId, compStyle) => {
  if (!dataModelId) {
    dataList.value = [];
    return false;
  }

  api.post('/business/data-field/list/' + dataModelId).then(res => {
    const fieldOptions = [];
    (res.data && res.data).forEach(field => {
      fieldOptions.push({key: field.fieldName, value: field.showName});
    });
    compStyle["fieldOptions"] = fieldOptions;
  });
};

const loadDataModelData = (dataModelId, compStyle) => {
  if (!dataModelId || !compStyle["value"] || !compStyle["label"]) {
    dataList.value = [];
    return;
  }
  api.post('/codeless/data-model/' + dataModelId + '/list').then(res => {
    const fieldValueOptions = [];
    (res.data && res.data).forEach(field => {
      fieldValueOptions.push({key: field[compStyle["value"]], value: field[compStyle["label"]]});
    });
    dataList.value = fieldValueOptions;
    compStyle["fieldValueOptions"] = fieldValueOptions;
  });
};

const loadValue = async() => {
  const dataList = (await visual.loadData(props.compData, {}, {}, currNode.value)).data || [];
  currNode.value.compData.dataList = JSON.stringify(dataList);
  const defaultValue = dataList.length > 0 && dataList[0]['内容'] || '';

  currValue.value = null;
  if (props.compStyle['multiple'] === true) {
    currValue.value = defaultValue ? defaultValue.split(',') : [];
  } else {
    currValue.value = defaultValue || '';
  }
};

watch(() => props.compStyle, () => {
  init();
}, {deep: true});

watch(() => props.compData?.refresh, () => {
  loadValue();
});

onMounted(() => {
  init();
  loadValue();
});
</script>

<style scoped>
.vc-select {
  min-width: 100px;
}
</style>